import { login, logout, getInfo as getInfoFun } from '@/api/login';
import { GetAllUserKeyList } from '@/api/system/user';
import {
  getToken,
  setToken,
  removeToken,
  setRefeshToken,
  getRefeshToken,
  removeRefeshToken
} from '@/utils/auth';
import defAva from '@/assets/images/profile.jpg';
import { EditUser } from '@/api/system/user';
import {
  ElMessage,
  ElMessageBox,
  ElNotification,
  ElLoading
} from 'element-plus';
import { addFileHead } from '@/views/components/function/common';
import { showToast } from 'vant';
import router from '@/router/index';
import { isMobile } from '@/utils/request';
const useUserStore = defineStore('user', {
  state: () => ({
    Token: getToken(),
    Avatar: '',
    roles: [],
    permissions: [],
    userInfo: {},
    cancelTokenArr: [],
    RefreshToken: getRefeshToken(),
    allUserList: []
  }),
  actions: {
    addCancelToken(cancel) {
      if (!this.cancelTokenArr) {
        this.cancelTokenArr = [];
      }
      if (cancel) {
        this.cancelTokenArr.push(cancel);
      }
    },
    // 取消所有请求
    clearCancelToken() {
      this.cancelTokenArr.forEach(c => {
        if (c) {
          c();
        }
      });
      this.cancelTokenArr = [];
    },
    //修改头像
    editUserAvatar(Avatar) {
      this.Avatar = addFileHead(Avatar);
    },
    //修改stroe用户
    editStoreUser(info) {
      this.Avatar = addFileHead(info.Avatar);
      this.userInfo = info;
    },
    //修改用户信息
    editUserInfo(userInfo) {
      return new Promise((resolve, reject) => {
        EditUser(userInfo)
          .then(res => {
            this.Avatar = userInfo.Avatar;
            this.userInfo = userInfo;
            ElMessage.success('修改成功');
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 登录
    login(userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(res => {
            setToken(res.data.Token);
            setRefeshToken(res.data.RefreshToken);
            this.Token = res.data.Token;
            this.RefreshToken = res.data.RefreshToken;
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        GetAllUserKeyList().then(res => {
          this.allUserList = res.data;
        });
        getInfoFun().then(res => {
          if (res?.status != 401 && res?.status != 0) {
            removeToken();
            removeRefeshToken();
            let str = '用户信息错误，请重新登录';
            if (isMobile) {
              showToast(str);
              setTimeout(() => {
                router.push({ path: '/login', query: { state: 'bind' } });
              }, 1500);
            } else {
              ElMessage.error(str);
              setTimeout(() => {
                router.push({
                  path: '/login',
                  query: { redirect: location.pathname }
                });
              }, 1500);
            }
            return;
          }
          const user = res.data;
          this.userInfo = res.data;
          console.log(user);
          const Avatar =
            user.Avatar == '' || user.Avatar == null
              ? defAva
              : addFileHead(user.Avatar);

          if (res.roles && res.roles.length > 0) {
            // 验证返回的roles是否是一个非空数组
            this.roles = res.roles;
            this.permissions = res.permissions;
          } else {
            this.roles = ['ROLE_DEFAULT'];
          }
          this.Avatar = Avatar;

          resolve(res);
        });
        // .catch(error => {

        //   reject(error);
        // });
      });
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        // logout(this.Token)
        // .then(() => {
        this.Token = '';
        this.roles = [];
        this.permissions = [];
        removeToken();
        removeRefeshToken();
        resolve();
        // })
        // .catch((error) => {
        //   reject(error);
        // });
      });
    }
  }
});

export default useUserStore;
